package com.xianggu.protocol.clint;

import com.xianggu.protocol.EnumConstants;
import com.xianggu.protocol.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author chengjy
 * @date 2025/3/8
 */
public class HttpClint {
    public static String sent(Invocation invocation, String hostName , Integer prot){
        // 构建请求

        try {
            URL url = new URL("http",hostName , prot, EnumConstants.NETWORK_PATH);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);

            OutputStream outputStream = urlConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            oos.writeObject(invocation);

            oos.flush();
            oos.close();

            // 阻塞获取结果
            InputStream inputStream = urlConnection.getInputStream();
            return IOUtils.toString(inputStream);

        } catch (MalformedURLException e) {
            throw new RuntimeException("构建请求失败！"+e);
        } catch (IOException e) {
            throw new RuntimeException("请求链接失败！"+e);
        }
    }
}
